import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store/index";
import { getToken } from "@/utils/storage";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, //URL地址   环境变量文件 .env.development
  timeout: 8000, //超时
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (getToken()) {
      // 设置令牌请求头
      config.headers["AuthToken"] = getToken();
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 相应拦截
service.interceptors.response.use(
  // 通过自定义code 判定响应状态 也可以通过HTTP状态码判断
  (response) => {
    const res = response.data;
    // code 不为0 则判断为一个错误
    if (res.code !== 200) {
      if (res.code === 504 || res.code === 501) {
        Message({
          message: res.mes || "Error",
          type: "error",
          duration: 5 * 1000,
        });
      }
      return Promise.reject(new Error(res.mes || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
  }
);

export default service;
